package com.bwie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.bwie.common.constants.Constants;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.response.LoginResponse;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import com.bwie.exception.LoginException;
import com.bwie.remote.UserRemote;
import com.bwie.service.LoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @className: LoginServiceImpl
 * @Description: TODO
 * @version: v1.８.0
 * @author: 刘茂锴
 * @date: 2025/10/2 10:53
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private UserRemote userRemote;
    @Autowired
    private RedisTemplate redisTemplate;

    //用户名密码登录
    @Override
    public LoginResponse loginUser(User user) {
        Result<User> userResult = userRemote.selectUser(user);
        if (userResult.getCode()== Constants.ERROR){
            throw new LoginException("远程调用用户信息失败");
        }
        User loginUser = userResult.getData();
        if (loginUser==null){
            throw new LoginException("用户不存在");
        }

        Map<String, Object> map = new HashMap<>();
        //生成唯一标识
        String userKey = IdUtil.fastSimpleUUID();
        map.put(JwtConstants.USER_KEY,userKey);
        //生成token
        String token = JwtUtils.createToken(map);
        //将用户信息存入到redis中
        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey,loginUser,30, TimeUnit.MINUTES);

        LoginResponse loginResponse = new LoginResponse();
        loginResponse.setToken(token);
        loginResponse.setShiJ("30MIN");
        return loginResponse;
    }
}
